package com.share.hope.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.share.hope.entity.PostsInfo;
import com.share.hope.entity.page.Condition;
import com.share.hope.entity.page.PageQuery;
import com.share.hope.entity.page.PageQueryVo;
import com.share.hope.entity.result.PageR;
import com.share.hope.entity.result.R;
import com.share.hope.mapper.PostsInfoMapper;
import com.share.hope.service.CommentInfoService;
import com.share.hope.service.LikesPostsService;
import com.share.hope.service.PostsInfoService;
import com.share.hope.service.UserInfoService;
import com.share.hope.vo.PostsPageQueryVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Map;

@Service
@Slf4j
@RequiredArgsConstructor
public class PostsInfoServiceImpl extends BaseServiceImpl<PostsInfoMapper, PostsInfo> implements PostsInfoService {

    private final CommentInfoService commentInfoService;

    private final UserInfoService userInfoService;

    private final LikesPostsService likesPostsService;

    @Override
    public R<String> createPostsInfo(PostsInfo postsInfo) {
        if (this.save(postsInfo)) {
            return R.ok("发表成功");
        }
        return R.error("发表失败");
    }

    @Override
    public R<String> updatePostsInfo(PostsInfo postsInfo) {
        if (this.updateById(postsInfo)) {
            return R.ok("修改成功");
        }
        return R.error("修改失败");
    }

    @Override
    public R<String> deletePostsInfo(Long id) {
        if (this.removeById(id)) {
            return R.ok("删除成功");
        }
        return R.error("删除失败");
    }

    @Override
    public R<PageR<PostsInfo>> pagePostsInfo(PageQueryVo<PostsPageQueryVo> queryVo) {
        log.info("[pagePostsInfo] input is: {}", queryVo);

        LambdaQueryWrapper<PostsInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(PostsInfo::getCreateTime);

        Map<Long, Long> CommentCount = commentInfoService.getCount();
        Map<Long, Long> likesCount = likesPostsService.getCount();

        IPage<PostsInfo> page = this.page(Condition.getPage(queryVo.getPage()), wrapper);
        page.getRecords().forEach(item -> {
            item.setComment(commentInfoService.getComment(item.getId()));
            item.setComments(CommentCount.getOrDefault(item.getId(), 0L));
            item.setLikes(likesCount.getOrDefault(item.getId(), 0L));
        });

        return R.success(new PageR<>(page));
    }
}
